/*
 * @Description:
 * @Autor: lcz
 * @LastEditors: lcz
 * @LastEditTime: 2024-01-16 14:23:45
 */

import React, { useEffect } from 'react';
import { Prompt } from 'react-router-dom';

import type { FormPromptProps } from './interface';
import useGetFieldsValue from './useGetFieldsValue';
const FormPrompt = ({
  hasUnsavedChanges,
  message = '你还有未更改的操作,确认离开吗?',
}: FormPromptProps) => {
  useEffect(() => {
    const onBeforeUnload = (e: BeforeUnloadEvent) => {
      if (hasUnsavedChanges) {
        e.preventDefault();
        e.returnValue = '';
      }
    };
    window.addEventListener('beforeunload', onBeforeUnload);
    return () => {
      window.removeEventListener('beforeunload', onBeforeUnload);
    };
  }, [hasUnsavedChanges]);

  return <Prompt when={hasUnsavedChanges} message={message} />;
};

FormPrompt.useGetFieldsValue = useGetFieldsValue;

export default FormPrompt;
